import $cache from '@/plugins/cache'
import Event from '../_event'
import Menu from '@/types/entity/Menu'
import Route from '@/router/entity/Route'
export default class MenuStore {
  menuList: Menu[]
  hasRoutes = false
  private MENULIST_CACHE_KEY = 'MENULIST_CACHE_KEY'
  public readonly EVENT_MENUS_CHANGE = new Event()
  constructor() {
    this.menuList = $cache.local.get(this.MENULIST_CACHE_KEY)
  }
  setMenuList(menuList: Menu[]) {
    this.menuList = menuList
    $cache.local.set(this.MENULIST_CACHE_KEY, menuList)
    // 触发重新加载路由
    this.EVENT_MENUS_CHANGE.emit()
  }
  getMenuList(): Menu[] {
    return this.menuList
  }
  private getChildrenMenus(menus: Menu[]): Menu[] {
    // this.menuList是树形的，需要转为平面的，无等级的
    if (menus == null || menus.length === 0) return []
    const result: Menu[] = []
    menus.forEach((menu) => {
      result.push(menu)
      result.push(...this.getChildrenMenus(menu.childrenMenus))
    })
    return result
  }
  getRouteListPlaneStructure(): Route[] {
    const routeList: Route[] = this.getChildrenMenus(this.menuList).map((menu) => {
      return {
        name: menu.name,
        path: menu.route,
        component: menu.component,
        meta: {
          label: menu.label
        }
      }
    })
    return routeList
  }
  clearMenuList(): void {
    this.menuList = null
    $cache.local.remove(this.MENULIST_CACHE_KEY)
  }
  setRoutesState(state: boolean) {
    this.hasRoutes = state
  }
}
